package org.sagemath.droid;

import java.util.LinkedList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.text.format.Formatter;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class InteractDiscreteSlider 
		extends InteractControlBase
		implements OnSeekBarChangeListener {
	private final static String TAG = "InteractDiscreteSlider";
	
	protected SeekBar seekBar;
	protected TextView nameValueText;
	
	public InteractDiscreteSlider(InteractView interactView, String variable, Context context) {
		super(interactView, variable, context);
		
		nameValueText = new TextView(context);
		nameValueText.setMaxLines(1);
		nameValueText.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f));
		nameValueText.setPadding(
				nameValueText.getPaddingLeft()+10, 
				nameValueText.getPaddingTop()+5, 
				nameValueText.getPaddingRight()+5, 
				nameValueText.getPaddingBottom());
		addView(nameValueText);
		
		seekBar = new SeekBar(context);
		seekBar.setMax(1);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, 
				LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
		seekBar.setLayoutParams(params);
		addView(seekBar);
		seekBar.setOnSeekBarChangeListener(this);
	}
	
	private LinkedList<String> values = new LinkedList<String>();
	
	public void setValues(LinkedList<String> values) {
		this.values = values;
		seekBar.setMax(this.values.size()-1);
		updateValueText();
	}

	public void setValues(JSONObject control) {
		this.values.clear();
		try {
			JSONArray values= control.getJSONArray("values");
			for (int i=0; i<values.length(); i++)
				this.values.add( values.getString(i) );
				
		} catch (JSONException e) {
			Log.e(TAG, e.getLocalizedMessage());
			this.values.add("0");
			this.values.add("1");
		}
		seekBar.setMax(this.values.size()-1);
		updateValueText();
	}

	public Integer getValue() {
		int raw = seekBar.getProgress();
		return raw;
	}
	
	private void updateValueText() {
		nameValueText.setText(getVariableName() + "=" + values.get(getValue()));		
	}
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		updateValueText();
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		interactView.notifyChange(this);
	}
}
